//
//  SKNetworkTools.swift
//  WeiboProjectYL
//
//  Created by yanli on 16/7/10.
//  Copyright © 2016年 mountainPassCell. All rights reserved.
//

import UIKit
import AFNetworking  //导入第三方框架

// 定义请求类型的枚举,默认值从0开始
enum RequestType: Int {
    case GET
    case POST
}



//网路工具类
class SKNetworkTools:  AFHTTPSessionManager{
    
    // 单例全局访问点
    static let shareTools: SKNetworkTools = {
            let tools = SKNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    // 封装get / post 请求
    func request(type: RequestType,url: String,params: AnyObject?, callBack:(responder: AnyObject?,error: NSError?)->()) {
        //判断用哪种发送请求的方法
        if type == .GET {
            GET(url, parameters: params, progress: nil, success: { (_, responder) -> Void in
                
                callBack(responder: responder, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                callBack(responder: nil, error: error)
            })
        } else {  //POST 请求方法
            POST(url, parameters: params, progress: nil, success: { (_, responder) -> Void in
                
                callBack(responder: responder, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    callBack(responder: nil, error: error)
                    
            })
        }
    }
}



//  OAuth 登录相关接口
extension SKNetworkTools {
    //通过 授权码(code)获取accesstoken令牌
    func requestAccesstoken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        //准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //准备参数
        let params = [
            "client_id" : WeiboAppKey,
            "client_secret" : WeiboAppSecret,
            "grant_type" : "authorization_code",
            "code": code,
            "redirect_uri" : WeiboRedirect_Uri
        ]
        
        //使用通用接口去请求
        request(.POST, url: url, params: params, callBack: callBack)
    }
    
    
    // 获取用户信息
    func requestUserInfo(userAccount: SKUserAccount, callBack:(response: AnyObject?, error: NSError?) -> ()) {
        
        // 请求接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        // 准备请求参数
        // int 64,跟字符串放在一起编译不通过,需要转换成字符串
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        
        //使用通用接口去请求
        request(.GET, url: url, params: params, callBack: callBack)
        
    }
    
    
}


// MARK:    -- 发送微博相关接口
extension SKNetworkTools {
    
    /**
     发送图片微博接口
     
     - parameter access_token: 访问令牌
     - parameter status:       微博内容
     - parameter image:        上传的图片
     - parameter callBack:     数据回调
     */
    func upload(access_token: String, status: String, image: UIImage, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备url地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        //        let imageData = UIImagePNGRepresentation(image)
        //        imageData?.writeToFile("/Users/whitcast/Desktop/1.png", atomically: true)
        //  compressionQuality质量系数  0-1, 系数越小质量越低
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        
        //  上传图片接口
        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            
            }, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }
        
    }
    
    
    
    /**
     发送文字微博接口
     
     - parameter access_token: 访问令牌
     - parameter status:       微博内容
     - parameter callBack:     数据回调
     */
    func update(access_token: String, status: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //  准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        //  使用共有函数进行网络请求数据
        request(.POST, url: url, params: params, callBack: callBack)
    }
    
}
    
    




// MARK:    -- 首页微博相关接口
extension SKNetworkTools {
    /**
     获取微博数据
     
     - parameter maxId:    上拉加载所需要的微博id, 注意数据重复
     - parameter callBack: 数据回调
     */
    func loadStatus(maxId: Int64 = 0, sinceId: Int64 = 0,callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //  准备参数
        let params = [
            "access_token": SKUserAccountViewModel.shareUserAccount.accessToken!,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        
        print(url + "?access_token=" + SKUserAccountViewModel.shareUserAccount.accessToken!)
        
        request(.GET, url: url, params: params, callBack: callBack)
        
        
    }
    
}












